<template>
  <div class="app-container">
    <!--  弹出框开始  -->
    <el-dialog
      :visible.sync="PurchaseDialogVisible"
      width="80%"
      top="10vh"
      style="height: 100%"
      :title="dialogTitle"
    >
      <PurchaseOrderForm :order-form="orderForm" :edit="formEdit" />
      <div style="height: 65vh">
        <el-card class="cardTable">
          <common-table
            :table-data="detailTableData"
            :table-column="detailTableKeys"
            :is-dialog="true"
            table-index="index"
            @handleRowDoubleClick="handleRowDoubleClick"
            @dialogDel="deletePurchaseOrderDetail"
            @handleSelect="innerHandSelect"
          />
        </el-card>
      </div>
      <div v-show="orderForm.origin_status !== 4" slot="footer" class="dialog-footer">
        <el-button @click="PurchaseDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="detailSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!--  弹出框结束  -->
    <!--  查询开始  -->
    <el-row type="fixed">
      <el-col span="3">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="openDialog('add')">新增</el-button>
      </el-col>
      <el-col span="18">
        <el-form :inline="true" :model="params" class="demo-form-inline">
          <el-form-item label="搜索">
            <el-input v-model="params.search" placeholder="订单号" size="small" />
          </el-form-item>
          <el-form-item label="供应商">
            <el-select v-model="params.search" size="small">
              <el-option
                v-for="(item, index) in $store.state.basic_data.suppliers"
                :key="index"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" icon="el-icon-search" @click="onSearch">查询</el-button>
            <el-button type="primary" size="small" icon="el-icon-refresh-left" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col span="3">
        <h2>采购退货</h2>
      </el-col>
    </el-row>
    <!--  查询结束  -->
    <!--  展示表格开始  -->
    <el-card
      class="cardTable"
    >
      <commonTable
        :table-data="tableData"
        :table-column="tableKeys"
        :table-index="'index'"
        :operate="true"
        @editRow="editPurchaseOrder"
        @deleteRow="deletePurchaseOrderHasTips"
      />
    </el-card>
    <!--  展示表格结束  -->
    <!--  分页开始  -->
    <el-row align="middle" type="flex" justify="center">
      <el-pagination
        :current-page="params.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="params.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChangePage"
      />
    </el-row>
    <!--  分页结束  -->
  </div>
</template>

<script>
import {
  PurchaseDetailSearchAPI,
  PurchaseDetailUpdateAPI,
  PurchaseOrderDetailReadAPI,
  PurchaseOrderReturnCreateAPI, PurchaseOrderReturnDeleteAPI,
  PurchaseOrderReturnItemCreateAPI,
  PurchaseOrderReturnItemListAPI,
  PurchaseOrderReturnItemUpdateAPI,
  PurchaseOrderReturnListAPI,
  PurchaseOrderReturnUpdateAPI
} from '@/api/purchases/purchase'
import PurchaseOrderForm from '@/components/form/PurchaseOrderForm.vue'
import commonTable from '@/components/table/commonTable'
import { generateOrderNumber } from '@/utils/generateOrderNumber'
import formatDate from '@/utils/formDate'
import { CLIENT_INFO } from '@/constants/CLIENT_INFO'
import { GoodsDetailAPI, GoodsPatchAPI } from '@/api/BasicData/goods'

export default {
  components: {
    PurchaseOrderForm,
    commonTable
  },
  data() {
    return {
      PurchaseDialogVisible: false,
      dialogTitle: '',
      params: {
        search: '',
        page_size: 10,
        page: 1
      },
      tableData: [],
      detailTableData: [],
      tableKeys: [
        { label: '退货单号', prop: 'purchase_return_code', visible: true, edit: false, type: 'string' },
        { label: '订单日期', prop: 'order_date', visible: true, edit: false, type: 'string' },
        { label: '供应商', prop: 'vendor_name', visible: true, edit: false, type: 'string' },
        { label: '订单状态', prop: 'status', visible: true, edit: true, type: 'select' },
        // { label: '订单总量', prop: 'order_total', visible: true, edit: false, type: 'string' },
        { label: '备注', prop: 'remark', visible: true, edit: true, type: 'string' }
        // { label: '要求交货日期', prop: 'requested_delivery_date', visible: true },
        // { label: '实际交货日期', prop: 'actual_delivery_date', visible: true }
      ],
      detailTableKeys: [
        { label: '采购订单', prop: 'purchase_order_code', visible: true, edit: false, type: 'string' },
        // { label: '订单日期', prop: 'update_time', visible: true, edit: true, type: 'date' },
        {
          label: '产品编号', prop: 'product_code', visible: true, edit: false, type: 'autocomplete'
        },
        { label: '产品名称', prop: 'product_name', visible: true, edit: false, type: 'string' },
        // { label: '产品规格', prop: 'product_specification', visible: true, edit: false, type: 'string' },
        { label: '颜色', prop: 'color', visible: true, edit: false, type: 'string' },
        { label: '订单数量', prop: 'quantity', visible: true, edit: false, type: 'number' },
        { label: '已送数量', prop: 'has_received_quantities', visible: true, edit: false, type: 'number' },
        { label: '已退数量', prop: 'has_returned_quantities', visible: true, edit: false, type: 'number' },
        { label: '退货数量', prop: 'quantity_returned', visible: true, edit: true, type: 'number' },
        { label: '退货原因', prop: 'reason', visible: true, edit: true, type: 'string' }
        // { label: '实际交货日期', prop: 'actual_delivery_date'
      ],
      originTableData: [],
      orderForm: {
        order_code: '',
        vendor: '',
        order_date: '',
        order_status: '',
        origin_status: null
        // ... other form fields
      },
      total: 0,
      formEdit: true
      // ... other data properties
    }
  },
  async created() {
    await this.refreshPage(this.params)
  },
  methods: {
    async refreshPage(params) {
      // ... API call to fetch orders

      const orders = await PurchaseOrderReturnListAPI(params)
      this.total = +orders.count
      // console.log(orders)
      this.tableData = orders.results.map(item => ({
        ...item,
        order_date: item.create_time.slice(0, 10),
        vendor_name: this.$store.state.basic_data.suppliers.find(item1 => item1.id === item.vendor)?.name,
        order_status: this.$store.state.basic_data.ORDER_STATUS.find(item1 => item1.id === item.status)?.id,
        status: this.$store.state.basic_data.ORDER_STATUS.find(item1 => item1.id === item.status)?.name,
        edit: false
      }))
      // this.tableData.push({ edit: true })
      this.originTableData = this.tableData.map(item => ({ ...item }))
    },
    onSearch() {
      this.refreshPage(this.params)
    },
    onReset() {
      this.params.search = ''
      this.refreshPage(this.params)
    },
    async openDialog(status, selectedRow) {
      this.PurchaseDialogVisible = true
      if (status === 'add') {
        this.dialogTitle = '新增退货单'
        this.formEdit = true
        this.orderForm = {
          order_code: generateOrderNumber('R' + CLIENT_INFO.code),
          vendor: CLIENT_INFO.id,
          order_date: formatDate(new Date()),
          order_status: 1
        } // Reset form
        const res = await PurchaseDetailSearchAPI({ vendor: CLIENT_INFO.name, page_size: 1000 })
        this.detailTableData = res.results.map(item => {
          const product = this.$store.state.basic_data.products.find(item1 => item1.id === item.product)
          return {
            ...item,
            product_code: product.goods_id,
            product_name: product.name,
            product_specification: product.code,
            color: product.color,
            edit: false
          }
        })
        this.form = {} // Reset form
      } else if (status === 'edit') {
        this.dialogTitle = '编辑退货单'
        this.formEdit = false
        // console.log(selectedRow)
        this.orderForm = {
          ...selectedRow,
          order_code: selectedRow.purchase_return_code,
          origin_status: selectedRow.order_status
        } // Copy selected row data to form
        const res = await PurchaseOrderReturnItemListAPI({
          purchase_return_code: selectedRow.purchase_return_code,
          page_size: 1000
        })
        this.detailTableData = res.results.map(async item => {
          const res1 = await PurchaseOrderDetailReadAPI(item.purchase_order_detail)
          const product = this.$store.state.basic_data.products.find(item1 => item1.id === res1.product)
          return {
            ...item,
            quantity: res1.quantity,
            purchase_order_code: res1.purchase_order_code,
            product_id: product.id,
            product_code: product.goods_id,
            product_name: product.name,
            product_specification: product.code,
            has_received_quantities: res1.has_received_quantities, // 新增已收货数量字段
            has_returned_quantities: this.orderForm.order_status === 4
              ? res1.has_returned_quantities - item.quantity_returned
              : res1.has_returned_quantities, // 新增已收货数量字段
            color: product.color,
            order_status: this.orderForm.order_status,
            edit: false
          }
        })
        await Promise.all(this.detailTableData).then(res => {
          this.detailTableData = res
        })
        // console.log(this.detailTableData)
        this.detailTableData.push({
          product_code: '',
          product_name: '',
          product_specification: '',
          color: '',
          quantity: null,
          remark: '',
          add: true,
          edit: false
        })
      }
    },
    editPurchaseOrder(row) {
      // ... logic to edit a purchase order
      this.openDialog('edit', row)
    },
    handleCurrentChangePage(val) {
      // ... logic to handle page change
      this.params.page = val
      this.refreshPage(this.params)
    },
    handleSizeChange(val) {
      this.params.page_size = val
      this.refreshPage(this.params)
    },
    handleRowDoubleClick(row) {
      // ... other methods
      // console.log(row)
    },
    async detailSubmit() {
      if (this.dialogTitle === '新增退货单') {
        this.orderForm.status = +this.orderForm.order_status
        this.orderForm.purchase_return_code = this.orderForm.order_code
        await PurchaseOrderReturnCreateAPI(this.orderForm)
        for (const item of this.detailTableData) {
          console.log(1314)
          console.log(item)
          if (item.quantity_returned > 0) {
            item.purchase_return_code = this.orderForm.purchase_return_code
            item.purchase_order_detail = item.id
            await PurchaseOrderReturnItemCreateAPI(item)
            // console.log(this.detailTableData)
          }
        }
        this.$message.success('提交成功')
        this.PurchaseDialogVisible = false
        await this.refreshPage(this.params)
      } else if (this.dialogTitle === '编辑退货单') {
        this.orderForm.status = this.orderForm.order_status
        delete this.orderForm.notes
        await PurchaseOrderReturnUpdateAPI(this.orderForm)
        for (const item of this.detailTableData.slice(0, -1)) {
          item.purchase_return_code = this.orderForm.purchase_return_code
          item.order_date = this.orderForm.order_date
          item.product = item.product_id
          if (!item.add) {
            await PurchaseOrderReturnItemUpdateAPI(item)
          } else {
            await PurchaseOrderReturnItemCreateAPI(item)
          }
          if (this.orderForm.status === 4) {
            item.id = item.purchase_order_detail
            const upData = {
              id: item.purchase_order_detail,
              has_returned_quantities: item.quantity_returned + item.has_returned_quantities
            }
            await PurchaseDetailUpdateAPI(upData)
            // 更新产品库存
            await this.updateGoodsDefectiveQuantity(item.product, item.quantity_returned)
          }
        }

        this.$message.success('提交成功')
        this.PurchaseDialogVisible = false
        await this.refreshPage(this.params)
      }
    },
    deletePurchaseOrderHasTips(row) {
      this.$confirm('此操作将永久删除该订单,无法恢复, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await PurchaseOrderReturnItemListAPI(row)
        console.log(res)
        if (row.order_status === 4) {
          for (const item of res.results) {
            const origin = await PurchaseOrderDetailReadAPI(item.purchase_order_detail)
            console.log(origin)
            const upData = {
              id: item.purchase_order_detail,
              has_returned_quantities: origin.has_returned_quantities - item.quantity_returned
            }
            await PurchaseDetailUpdateAPI(upData)
            // 更新产品库存
            await this.updateGoodsDefectiveQuantity(origin.product, item.quantity_returned, true)
          }
        }
        await PurchaseOrderReturnDeleteAPI(row.purchase_return_code)
        // 删除订单会联级删除明细,不用重新删除
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        await this.refreshPage(this.params)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    deletePurchaseOrderDetail(row) {
      this.detailTableData.splice(this.detailTableData.indexOf(row), 1)
    },
    // 更新库存封装
    async updateGoodsDefectiveQuantity(goods_id, quantity, type) {
      const goodsDefectiveQuantity = (await GoodsDetailAPI(goods_id)).defective_quantity
      const goodsUpData = {
        id: goods_id,
        defective_quantity: type ? goodsDefectiveQuantity - quantity : goodsDefectiveQuantity + quantity
      }
      await GoodsPatchAPI(goodsUpData)
    },
    innerHandSelect() {
      this.detailTableData.push(
        {
          product_code: '',
          product_name: '',
          product_specification: '',
          color: '',
          quantity: null,
          remark: '',
          add: true,
          edit: false
        }
      )
    }
  }
}

</script>

<style lang="scss" scoped>
// ... styles
.app-container {
  height: 100%;
  display: flex;
  flex-direction: column;

  .cardTable {
    flex: 1;
    margin-bottom: 20px;
    height: 100%;

    ::v-deep .el-card__body {
      height: 100%;
    }
  }
}
</style>
